﻿
using System;
using System.Threading;
using System.Windows.Forms;
namespace ResourceReportBuilder
{
    public class SplashForm : Form
    {
        private static Thread _splashThread;
        private static SplashForm _splashForm;

        public SplashForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Show the Splash Screen (Loading...)
        /// </summary>
        public void ShowSplash(Form mainForm)
        {
            if (_splashThread == null)
            {
                mainForm.Load += new EventHandler(mainForm_Load);
                _splashThread = new Thread(new ThreadStart(DoShowSplash));
                _splashThread.IsBackground = true;
                _splashThread.Start();
            }
        }

        void mainForm_Load(object sender, EventArgs e)
        {
            Thread.Sleep(2000);
            CloseSplash();
            (sender as Form).Activate();
        }

        private void DoShowSplash()
        {
            if (_splashForm == null)
            {
                _splashForm = (SplashForm)Activator.CreateInstance(this.GetType());
            }

            Application.Run(_splashForm);
        }

        /// <summary>
        /// Close the splash (Loading...) screen
        /// </summary>
        private static void CloseSplash()
        {
            if (_splashForm == null)
            {
                return;
            }
            // need to call on the thread that launched this splash
            if (_splashForm.InvokeRequired)
            {
                _splashForm.Invoke(new MethodInvoker(CloseSplash));
            }
            else
            {
                Application.ExitThread();
            }
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // SplashForm
            // 
            this.ClientSize = new System.Drawing.Size(298, 215);
            this.Name = "SplashForm";
            this.ControlBox = false;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.TopMost = true;
            this.ResumeLayout(false);
        }
    }
}
